/**
 * Created by zhaocong on 2016/7/12.
 * 产品管理
 */
define(function (require, exports, module) {
  "use strict";
  var cc = window.cc || {};

  /**
   * 填写基本信息
   */
  cc.productAdd = function () {
    var self = this;

    self.bindEvents = function () {
      // 提示框
      $('.float-info').hover(function () {
        $(this).popover('show');
      }, function () {
        $(this).popover('hide');
      });
      // 选择地址
      $(document).on('click', function () {
        $('.datalist').hide();
      });
      $('.maplist').hover(function () {
        $(this).show();
      }, function () {
        $(this).hide();
      })
    };

    self.angularInit = function () {
      var app = angular.module('productAddApp', []);
      app.controller('productAdd', ['$scope', '$http', function ($scope, $http) {

        /**
         * 添加主标题
         * @type {Array}
         */
        $scope.contentTitleArr = [];
        $scope.contentTitle = '';
        $scope.addTitle = function () {
          var titleArr = [];
          $.each([$scope.countries, $scope.provinces, $scope.city, $scope.scenic, $scope.other], function (i, el) {
            titleArr.push(el ? el : '');
          });
          var title = titleArr.join('');
          if (title) {
            $scope.countries = '';
            $scope.provinces = '';
            $scope.city = '';
            $scope.scenic = '';
            $scope.other = '';
            var item = {name: title}
            $scope.contentTitleArr.push(item);
            contentTitle();
          }
        };
        // 移除一个主标题
        $scope.removeTitle = function (title) {
          var item = 0;
          $.each($scope.contentTitleArr, function (i, el) {
            if (el.name == title) item = i;
          });
          $scope.contentTitleArr.splice(item, 1);
          contentTitle();
          $(this).remove();
        }
        // 合成主标题
        function contentTitle() {
          var arr = [];
          $.each($scope.contentTitleArr, function (i, el) {
            arr.push(el.name);
          });
          $scope.contentTitle = arr.join('+');
        };

        /**
         * 搜索地址
         * @type {Array}
         */
        $scope.proMap = [];
        var inputEle = '';
        $scope.searchMap = function (type, key) {
          var data = {key: key, type: type};
          inputEle = type;
          $http.get('../../data/map.json', data)
              .success(function (req) {
                $scope.proMap = req.content;
                datalist();
              });
          function datalist() {
            var box = $(document.getElementById('proForm').elements[type]);
            $('.datalist').show().css({
              'min-width': box.outerWidth(true),
              'top': box.offset().top + 41,
              'left': box.offset().left
            });
          }
        };
        // 将搜索结果添加到Input框里
        $scope.touchMap = function (e) {
          $scope[inputEle] = e.target.innerHTML;
          $('.datalist').hide();
        };

        /**
         * 出发/目的地 地址查询 首字母查询
         * @type {Array}
         */
        $scope.words = [];
        $scope.mapList = [];
        for (var i = 0; i < 26; i++) {
          $scope.words.push(String.fromCharCode(65 + i)); //输出A-Z  26个大写字母
        }
        $scope.wordsMap = function (t, w) {
          var data = {t: t, w: w}
          $http.get('../../data/map.json', data)
              .success(function (req) {
                $scope.mapList = req.content;
              });
        };
        /* 启动时默认加载 */
        $scope.wordsMap('g', 'A');
        $scope.wordsMap('w', 'A');

        var mapVi = '';
        $scope.runMapli = function (e, vi) {
          e.stopPropagation();
          mapVi = vi;
          var mapinput = $(e.target || e.srcElement);
          console.log(mapinput.offset().top);
          $('.maplist').show().css({
            'top': mapinput.offset().top + 42,
            'left': mapinput.offset().left - (320 - mapinput.outerWidth())
          });
        };
        $scope.mapAdd = function (v) {
          $scope[mapVi] = v;
          $('.maplist').hide();
        };

        /**
         * 表单格式化
         * @type {{subtitle: $scope.pattern.subtitle}}
         */
        $scope.pattern = {
          subtitle: function (v) {
            if (v) $scope.subtitle = v.replace(/[<>‘’“”/\\!@#$%^&()！《》（）]/g, '');
          },
          day: function (t, v) {
            if (v < 0) $scope[t] = 0;
          }
        };

      }]);

      angular.bootstrap(document.body, ['productAddApp']);
    };

    /**
     * 启动
     */
    $(function () {
      self.bindEvents();
      self.angularInit();
    });
  };

  /**
   * 新增周边游-行程描述
   */
  cc.productAddStroke = function () {
    var self = this;

    /**
     * 初始化时间插件
     */
    self.time = function (ele) {
      var timer = ele || '.form_datetime';
      $(timer).datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: 2,
        format: "yyyy-mm-dd"
      });
    };
    self.time();

    /**
     * 上传图片
     */
    var bin = '.imgup';
    self.Image = require('./imageupload'); // 获取图片上传组件
    self.imgup = function () {
      self.Image.imageReset('../../data/com.php', bin);
    };
    self.imgup();

    var app = angular.module('strokeApp', []);
    app.controller('strokeCtrl', ['$scope', '$http', function ($scope, $http) {

      /**
       * 初始化一个行程
       * @type {*[]}
       */
      $scope.stroke = [{}, {}];
      // 向上提升一个位置
      $scope.strokeUp = function (i) {
        if (i > 0) {
          var tip = $scope.stroke[i];
          $scope.stroke[i] = $scope.stroke[i - 1];
          $scope.stroke[i - 1] = tip;
        }
      };
      // 向下移动一个位置
      $scope.strokeDown = function (i) {
        if (i < $scope.stroke.length - 1) {
          var tip = $scope.stroke[i];
          $scope.stroke[i] = $scope.stroke[i + 1];
          $scope.stroke[i + 1] = tip;
        }
      };
      // 添加一个行程
      $scope.strokeAdd = function (i) {
        $scope.stroke.splice(i + 1, 0, {});
        $('body').animate({scrollTop: $('body').scrollTop() + 200 + 'px'}, 300);
      };
      // 移除一个行程
      $scope.strokeSub = function (i) {
        if ($scope.stroke.length > 1) {
          $scope.stroke.splice(i, 1);
          $('body').animate({scrollTop: $('body').scrollTop() - 200 + 'px'}, 300);
        }
      };

      /**
       * 添加一个占位符，用于前台显示图标
       * @param i 下标
       * @param v 图标名称
       */
      $scope.tripset = function (i, v) {
        if (!$scope.stroke[i].trip) $scope.stroke[i].trip = '';
        $scope.stroke[i].trip += '{{' + v + '}}';
      };

      /**
       * 自愿购物活动补充协议
       * @type {*[]}
       */
      $scope.shopping = [{}];
      // 添加一个自愿购物
      $scope.addShowp = function () {
        $scope.shopping.push({});
      };
      // 删除一个自愿购物
      $scope.removeShowp = function (i) {
        $scope.shopping.splice(i, 1);
      };

      /**
       * 自愿参加另行付费旅游项目补充协议
       */
      $scope.project = [{}];
      // 添加一个协议
      $scope.addproject = function () {
        $scope.project.push({});
      };
      // 删除一个协议
      $scope.removeproject = function (i) {
        $scope.project.splice(i, 1);
      };

      // 每次都重新为time添加事件
      $scope.showTime = function (last) {
        last && self.time();
      };

      /**
       * 点击上传图片
       * @param e
       */
      $scope.imageUp = function (e) {
        var $this = $(e.target),
            fileId = $this.data('file'),
            file = $('#file' + fileId);
        file.trigger('click');
        file.on('change', function () {
          $('.tmp' + fileId).submit();
          $this.html('<i class="fa fa-refresh fa-spin fa-fw text-white"></i>');
          $this.removeClass('fa-image');
        });
        $('#tmpIframe').on('load', function () {
          var url = $.trim($(window.frames['tmpIframe'].document.body).html());
          $this.css({ 'background':'url('+url+') no-repeat center/cover'}).html('');
          $this.next().val(url);
          file.val('');
          file.off('change');
        });
      };

    }]);

    angular.bootstrap(document.body, ['strokeApp']);

  };


  module.exports = cc;
});